#include <cstdlib>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <math.h>
using namespace std;
#define N 1024
int c[N][N];//最优值
int b[N][N];//标记函
void LCSLength(int m, int n, char *x, char *y, int c[][N], int b[][N]) // 计算最优值
{                                                                // m=序列x长度，n=序列y长度。c:最长公共子序列长度；b:标记函数，追踪最优解
    int i, j;
    for (i = 1; i <= m; i++)
        c[i][0] = 0;
    for (i = 1; i <= n; i++)
        c[0][i] = 0;
    for (i = 1; i <= m; i++)
        for (j = 1; j <= n; j++)
        {
            if (x[i-1] == y[j-1])//x序列从x[0]开始,y序列从y[0]开始
            {
                c[i][j] = c[i - 1][j - 1] + 1;
                b[i][j] = 1;
            }
            else if (c[i - 1][j] >= c[i][j - 1]) // 上方的大
            {
                c[i][j] = c[i - 1][j];
                b[i][j] = 2;
            }
            else // 左方的大
            {
                c[i][j] = c[i][j - 1];
                b[i][j] = 3;
            }
        }
}

void LCS(int i, int j, char *x, int b[][N]) // 根据最优值构造最优解
{                                        // b:标记函数，追踪最优解
    if (i == 0 || j == 0)
        return;
    if (b[i][j] == 1) // 向左上
    {
        LCS(i - 1, j - 1, x, b);
        cout << x[i-1];//x序列从x[0]开始
    }
    else if (b[i][j] == 2) // 向上
        LCS(i - 1, j, x, b);
    else // 向左
        LCS(i, j - 1, x, b);
}

int main()
{
    int m, n;
    char x[N];
    char y[N];
    cout << "输入序列x:";
    cin >> x;
    cout << "输入序列y:";
    cin >> y;
    m = strlen(x);
    n = strlen(y);
    LCSLength(m, n, x, y, c, b);
    LCS(m, n, x, b);
    return 0;
}